<?php 

namespace Cli\Controller;

use Think\Log;
use Cli\Event\TaskEvent;


// +----------------------------------------------------------------------
// | 文件 TaskController.class.php
// +----------------------------------------------------------------------
// | 说明 常驻任务处理
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Author: 谢赤心 Legend. <xcx_legender@qq.com>
// +----------------------------------------------------------------------

class TaskController 
{
    private $serv;



    // static $cronRegister = [
    //     [ 1000, 'test'], // 每5分钟更新play
    // ];


    public function run()
    {
        $this->serv = new \swoole_server("127.0.0.1", 6060);
        $this->serv->set([
            'worker_num' => 4,   //一般设置为服务器CPU数的1-4倍
            // 'daemonize' => true,  //以守护进程执行
            'max_request' => 10000,
            'dispatch_mode' => 2,
            'task_worker_num' => 8,  //task进程的数量
            "task_ipc_mode " => 3 ,  //使用消息队列通信，并设置为争抢模式
            //"log_file" => "log/taskqueueu.log" ,//日志
        ]);

        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->start();
    }

    public function onStart( swoole_server $serv) {
        echo 'start..';
        // #TODO cron单独放
        // echo 'Start..';
        // $cronTable = [];
        // foreach (self::$cronRegister as $cron) {
        //     $cronTable[$cron[1]] = CronEvent::instance($cron[1]);
        //     if (!$cronTable[$cron[1]]){
        //         echo 'err';
        //         continue;
        //     }
        //     $cronEvent = $cronTable[$cron[1]];
        //     $serv->tick($cron[0], function() use($cronEvent)
        //     {
        //         $cronEvent->run();
        //     });
        // }
    }

    public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
        $serv->task( $data );
    }
    public function onTask($serv, $task_id, $from_id, &$data) {

        $data = json_decode($data, true);
        if (!$data){
            Log::record("[swoole] - [onTask]: warning: json_decode err", 'DEBUG');
            Log::save();
            return;
        }

        if (!$this->sign($data)){
            return;
        }
        TaskEvent::handle($data);
    }
    
    public function onFinish($serv,$task_id, $data) {
        // echo "Task {$task_id} finishn";
        // echo "Result: {$data}n";
    }

    protected function sign(&$data)
    {
        return true;
    }


}